package com.dx.mes.service.tool.service;

import com.dx.common.table.ppt.Bis_mtrl;
import com.dx.common.table.ppt.Ret_mtrl_aply;
import com.dx.common.table.ppt.Ret_wh_mtrl;
import com.dx.mes.common.dao.IBisMtrlDao;
import com.dx.mes.common.dao.IRetMtrlAplyDao;
import com.dx.mes.common.dao.IRetWhMtrlDao;
import com.dx.mes.common.table.rtnBean.SimpleRtnBeen;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.tool.service.IMtpmtrlapyService;
import com.dx.mes.facade.tool.tx.Mtpmtrlapy.*;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;

/**
 * Created by admin on 2017/11/12.
 */
@Service("mtpmtrlapyService")
public class MtpmtrlapyService implements IMtpmtrlapyService {
    private LogUtils logUtils;
    private static String TX_NAME = T_MTPMTRLAPY;

    @Autowired
    private IBisMtrlDao bisMtrlDao;
    @Autowired
    private IRetWhMtrlDao retWhMtrlDao;
    @Autowired
    private IRetMtrlAplyDao retMtrlAplyDao;
    @Override
    public String subMainProc(String evt_no, String strInMsg) {
        AppContext.clear();
        AppContext.setCurrServiceName(MtpmtrlapyService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(MtpmtrlapyService.class);
        logUtils.info("[InTrx:" + strInMsg + "]");

        Session session = retWhMtrlDao.getCrSession();
        long rtnCode = _NORMAL;
        String outMsg = null;

        MtpmtrlapyI inTrx = new  MtpmtrlapyI();
        MtpmtrlapyO outTrx = new MtpmtrlapyO();
        outTrx.setTrx_id(TX_NAME);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
        outTrx.setType_id(TRX_OUT);
        try {
            inTrx = JacksonUtil.fromJson(strInMsg, MtpmtrlapyI.class);

            rtnCode = subMainProc2(inTrx, outTrx);
            if (rtnCode != _NORMAL) {
                TransactionAspectSupport.currentTransactionStatus()
                        .setRollbackOnly();
                outTrx.setRtn_code(String.valueOf(rtnCode));
            } else {
                outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
                outTrx.setRtn_mesg(RETURN_MESG_OK);
                session.flush();
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            outTrx.setRtn_mesg(ex.toString());
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            logUtils.error(Util.stackTraceToString(ex));
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outMsg + "]");
        }
        return outMsg;
    }

    private long subMainProc2(MtpmtrlapyI inTrx, MtpmtrlapyO outTrx) {
        long lRc = _NORMAL;
        char actionType = inTrx.getAction_flg().toCharArray()[0];
        switch (actionType) {
            case 'M': {
                    lRc = queryByMtrlFunc(inTrx, outTrx);//备品备件申请记录查询
                if (lRc != _NORMAL) {
                    return lRc;
                }
                break;
            }
            case 'N': {
                lRc = addByMtrlFunc(inTrx, outTrx);//备品备件申请登记
                if (lRc != _NORMAL) {
                    return lRc;
                }
                break;
            }
            case 'C': {
                lRc = delMtrlAplyFunc(inTrx, outTrx);//备品备件申请删除
                if (lRc != _NORMAL) {
                    return lRc;
                }
                break;
            }
            case 'O': {
                lRc = saveMtrlAplyFunc(inTrx, outTrx);//备品备件领用，借用，归还登记
                if (lRc != _NORMAL) {
                    return lRc;
                }
                break;
            }
            default: {
                outTrx.setRtn_mesg("Invalide type input: [" + actionType + "]");
                return E_MTPMTRLAPY_INVALID_INPUT;
            }
        }
        return lRc;
    }
    
    private long queryByMtrlFunc(MtpmtrlapyI inTrx, MtpmtrlapyO outTrx) {
        long lRc = _NORMAL;
        MtpmtrlapyIA iary = inTrx.getIary().get(0);
        String hql ="From Ret_mtrl_aply where 1=1";
        if(!Util.isSpaceCheck(iary.getApply_cate())){
            hql = hql + " and apply_cate ='" + iary.getApply_cate() + "'";
        }
        if(!Util.isSpaceCheck(iary.getApply_stat())){
            hql = hql + " and apply_stat ='" + iary.getApply_stat() + "'";
        }
        if(!Util.isSpaceCheck(iary.getMtrl_prod_id_fk())){
        	hql = hql + " and mtrl_prod_id_fk ='" + iary.getMtrl_prod_id_fk() + "'";
        }
        if(!Util.isSpaceCheck(inTrx.getEvt_usr())){
        	hql = hql + " and apply_usr ='" + inTrx.getEvt_usr() + "'";
        }
        if(!Util.isSpaceCheck(iary.getDest_shop())){
            hql = hql + " and dest_shop ='" + iary.getDest_shop() + "'";
        }
        List<Ret_mtrl_aply>  ret_mtrl_aplies = retMtrlAplyDao.find(hql);
        List<MtpmtrlapyOB>    orayBList = new ArrayList<>();
        for(Ret_mtrl_aply ret_mtrl_aply : ret_mtrl_aplies){
            MtpmtrlapyOB oaryB = new MtpmtrlapyOB();
            oaryB.setEvt_seq_id(ret_mtrl_aply.getEvt_seq_id());
            oaryB.setMtrl_prod_id_fk(ret_mtrl_aply.getMtrl_prod_id_fk());
            Bis_mtrl bis_mtrl = bisMtrlDao.get(ret_mtrl_aply.getMtrl_prod_id_fk());
            if(bis_mtrl!=null){
                oaryB.setMtrl_name(bis_mtrl.getMtrl_prod_dsc());
            }else{
            	oaryB.setMtrl_name("未知备品备件名称");
            }
            oaryB.setApply_cate(ret_mtrl_aply.getApply_cate());
            oaryB.setApply_usr(ret_mtrl_aply.getApply_usr());
            oaryB.setApply_timestamp(ret_mtrl_aply.getApply_timestamp());
            oaryB.setApply_mtrl_qty(ret_mtrl_aply.getApply_mtrl_qty());
            oaryB.setRelate_mtrl_qty(ret_mtrl_aply.getRelate_mtrl_qty());
            oaryB.setWait_repay_mtrl_qty(ret_mtrl_aply.getRelate_mtrl_qty() - ret_mtrl_aply.getAct_repay_mtrl_qty());
            oaryB.setForce_comp_flg(ret_mtrl_aply.getForce_comp_flg());
            oaryB.setEvt_note(ret_mtrl_aply.getEvt_note());
            oaryB.setDest_shop(ret_mtrl_aply.getDest_shop());
            orayBList.add(oaryB);
        }
        outTrx.setOaryB(orayBList);
        return lRc;
    }

    private long addByMtrlFunc(MtpmtrlapyI inTrx, MtpmtrlapyO outTrx) {
    	SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
        long lRc = _NORMAL;
        Timestamp gEvtTimestamp = Util.getCurrentTimestamp();
        List<MtpmtrlapyIA>  iaryList = inTrx.getIary();
        for(MtpmtrlapyIA iary : iaryList) {
        	//获取库存RET_WH_MTRL信息，检查申请数量不能超过剩余库存数量
        	Ret_wh_mtrl ret_wh_mtrl = new Ret_wh_mtrl();
        	rtnBeen = getRetWhMtrlFunc(iary.getMtrl_prod_id_fk(), iary.getMtrl_lot_id(),iary.getDest_shop());
     		if (rtnBeen.getlRc() != _NORMAL) {
                outTrx.setRtn_mesg(rtnBeen.getMsgBuf());
                 return rtnBeen.getlRc();
    		} else {
    			ret_wh_mtrl = (Ret_wh_mtrl) rtnBeen.getObj();
    		}
                
     		if(Double.valueOf(iary.getApply_mtrl_qty()) > 
     			ret_wh_mtrl.getMtrl_qty() - ret_wh_mtrl.getEvt_qty()){//申请数量不能超过库存剩余数量
     			outTrx.setRtn_mesg("申请数量[" + iary.getApply_mtrl_qty() 
     					+ "]不能超过库存数量[" + (ret_wh_mtrl.getMtrl_qty() - ret_wh_mtrl.getEvt_qty()) + "]");
     			return E_MTPMTRLAPY_INVALID_MTRL_QTY;
     		}

     		Ret_mtrl_aply ret_mtrl_aply = new Ret_mtrl_aply();
     		if (!Util.isSpaceCheck(iary.getEvt_seq_id())) {//主键不为空，表示是修改操作
     			ret_mtrl_aply = retMtrlAplyDao.get(iary.getEvt_seq_id());
     			if (ret_mtrl_aply != null) {
     				ret_mtrl_aply.setApply_timestamp(gEvtTimestamp);
     				ret_mtrl_aply.setApply_usr(inTrx.getEvt_usr());
                    ret_mtrl_aply.setApply_mtrl_qty(Double.valueOf(iary.getApply_mtrl_qty()));
                    ret_mtrl_aply.setApply_cate(iary.getApply_cate());
                    ret_mtrl_aply.setEvt_note(iary.getEvt_note());
                    ret_mtrl_aply.setEvt_timestamp(gEvtTimestamp);
                    ret_mtrl_aply.setDest_shop(iary.getDest_shop());
                    ret_mtrl_aply.setEvt_usr(inTrx.getEvt_usr());
     			} else {
     				outTrx.setRtn_mesg("备品备件申请信息不存在");
     				return E_MTPMTRLAPY_MTRL_APLY_NOT_FOUND;
     			}
     		} else {//主键为空，表示是新增操作
     			ret_mtrl_aply.setEvt_seq_id(GUIDGenerator.javaGUID());
     			ret_mtrl_aply.setApply_timestamp(gEvtTimestamp);
     			ret_mtrl_aply.setApply_usr(inTrx.getEvt_usr());
     			ret_mtrl_aply.setApply_mtrl_qty(Double.valueOf(iary.getApply_mtrl_qty()));
     			ret_mtrl_aply.setApply_stat("INPR");
     			ret_mtrl_aply.setApply_cate(iary.getApply_cate());
     			ret_mtrl_aply.setEvt_note(iary.getEvt_note());
     			ret_mtrl_aply.setMtrl_prod_id_fk(iary.getMtrl_prod_id_fk());
     			ret_mtrl_aply.setEvt_timestamp(gEvtTimestamp);
     			ret_mtrl_aply.setEvt_usr(inTrx.getEvt_usr());
     			ret_mtrl_aply.setRelate_mtrl_qty(Double.valueOf(0));
     			ret_mtrl_aply.setAct_repay_mtrl_qty(Double.valueOf(0));
     			ret_mtrl_aply.setDest_shop(iary.getDest_shop());
     		}
     		retMtrlAplyDao.saveOrUpdate(ret_mtrl_aply);
        }
        return lRc;
    }
    
    private long delMtrlAplyFunc(MtpmtrlapyI inTrx, MtpmtrlapyO outTrx) {
        long lRc = _NORMAL;
        List<MtpmtrlapyIA>  iaryList = inTrx.getIary();
        for(MtpmtrlapyIA iary : iaryList) {
          Ret_mtrl_aply  ret_mtrl_aply = retMtrlAplyDao.get(iary.getEvt_seq_id());
            if (ret_mtrl_aply != null) {
                retMtrlAplyDao.delete(ret_mtrl_aply);
            } else {
                outTrx.setRtn_mesg("备品备件申请信息不存在");
                return E_MTPMTRLAPY_MTRL_APLY_NOT_FOUND;
            }
        }
        return lRc;
    }
    
    private long saveMtrlAplyFunc(MtpmtrlapyI inTrx, MtpmtrlapyO outTrx) {
    	SimpleRtnBeen rtnBeen = new SimpleRtnBeen(_NORMAL);
        long lRc = _NORMAL;
        Timestamp gEvtTimestamp = Util.getCurrentTimestamp();
        List<MtpmtrlapyIA>  iaryAList = inTrx.getIary();
        List<MtpmtrlapyIB>  iaryBList = inTrx.getIaryB();
        for(MtpmtrlapyIA iary : iaryAList) {//借用/领用登记
            Ret_mtrl_aply  ret_mtrl_aply = retMtrlAplyDao.get(iary.getEvt_seq_id());
            if (ret_mtrl_aply != null) {
            	if(!"INPR".equals(ret_mtrl_aply.getApply_stat())){
                    outTrx.setRtn_mesg("备品备件申请信息已经处理，无法继续登记操作");
                    return E_MTPMTRLAPY_INVALID_APPLY_STAT;
            	}
            	
            	//检查登记数量不能超过申请数量
            	if(Double.valueOf(iary.getRelate_mtrl_qty()) > ret_mtrl_aply.getApply_mtrl_qty()){
            		outTrx.setRtn_mesg("登记数量[" + iary.getRelate_mtrl_qty() 
                    		+ "]不能超过申请数量[" + ret_mtrl_aply.getApply_mtrl_qty() + "]");
                    return E_MTPMTRLAPY_INVALID_MTRL_QTY;
            	}
            	
                ret_mtrl_aply.setEvt_usr(inTrx.getEvt_usr());
                ret_mtrl_aply.setEvt_timestamp(gEvtTimestamp);
                ret_mtrl_aply.setRelate_mtrl_qty(Double.valueOf(iary.getRelate_mtrl_qty()));
                ret_mtrl_aply.setRepay_timestamp(Util.String2Timestamp(iary.getRepay_timestamp() + " 00:00:00"));
                if("L".equals(ret_mtrl_aply.getApply_cate())){
                    ret_mtrl_aply.setApply_stat("WAIT");
                }else{
                    ret_mtrl_aply.setApply_stat("COMP");
                }
                ret_mtrl_aply.setRelate_usr(inTrx.getEvt_usr());
                ret_mtrl_aply.setRelate_timestamp(gEvtTimestamp);
                retMtrlAplyDao.update(ret_mtrl_aply);
                
                //更新RET_WH_MTRL信息
                Ret_wh_mtrl ret_wh_mtrl = new Ret_wh_mtrl();
                rtnBeen = getRetWhMtrlFunc(ret_mtrl_aply.getMtrl_prod_id_fk(), ret_mtrl_aply.getMtrl_lot_id(),ret_mtrl_aply.getDest_shop());
                if (rtnBeen.getlRc() != _NORMAL) {
                	outTrx.setRtn_mesg(rtnBeen.getMsgBuf());
                    return rtnBeen.getlRc();
                } else {
                	ret_wh_mtrl = (Ret_wh_mtrl) rtnBeen.getObj();
                }
        		if(Double.valueOf(iary.getRelate_mtrl_qty()) > 
            		ret_wh_mtrl.getMtrl_qty() - ret_wh_mtrl.getEvt_qty()){//登记数量不能超过库存剩余数量
                    outTrx.setRtn_mesg("登记数量[" + iary.getRelate_mtrl_qty() 
                    		+ "]不能超过库存剩余数量[" + (ret_wh_mtrl.getMtrl_qty() - ret_wh_mtrl.getEvt_qty()) + "]");
                    return E_MTPMTRLAPY_INVALID_MTRL_QTY;
        		}
        		
                ret_wh_mtrl.setEvt_qty(ret_wh_mtrl.getEvt_qty() + Double.valueOf(iary.getRelate_mtrl_qty()));
                retWhMtrlDao.update(ret_wh_mtrl);
            } else {
                outTrx.setRtn_mesg("备品备件申请信息不存在");
                return E_MTPMTRLAPY_MTRL_APLY_NOT_FOUND;
            }
        }
        for(MtpmtrlapyIB iary : iaryBList) {//借用归还
            Ret_mtrl_aply  ret_mtrl_aply = retMtrlAplyDao.get(iary.getEvt_seq_id());
            if (ret_mtrl_aply != null) {
            	//归还数量不能超过剩余归还数量
            	if(Double.valueOf(iary.getAct_repay_mtrl_qty()) > 
            		ret_mtrl_aply.getRelate_mtrl_qty() - ret_mtrl_aply.getAct_repay_mtrl_qty()){
            		outTrx.setRtn_mesg("归还数量[" + iary.getAct_repay_mtrl_qty() 
                    		+ "]不能超过剩余归还数量[" + (ret_mtrl_aply.getRelate_mtrl_qty() - ret_mtrl_aply.getAct_repay_mtrl_qty()) + "]");
                    return E_MTPMTRLAPY_INVALID_MTRL_QTY;
            	}
                ret_mtrl_aply.setEvt_usr(inTrx.getEvt_usr());
                ret_mtrl_aply.setEvt_timestamp(gEvtTimestamp);
                ret_mtrl_aply.setAct_repay_mtrl_qty(ret_mtrl_aply.getAct_repay_mtrl_qty() + Double.valueOf(iary.getAct_repay_mtrl_qty()));
                ret_mtrl_aply.setAct_repay_timestamp(gEvtTimestamp);
                ret_mtrl_aply.setForce_comp_flg(iary.getForce_comp_flg());
                //强制结束或者归还数量和借出数量相等时，申请状态变为COMP
                if("Y".equals(iary.getForce_comp_flg()) || 
                		Double.doubleToLongBits(ret_mtrl_aply.getAct_repay_mtrl_qty()) == Double.doubleToLongBits(ret_mtrl_aply.getRelate_mtrl_qty())){
                    ret_mtrl_aply.setApply_stat("COMP");
                }
                retMtrlAplyDao.update(ret_mtrl_aply);
                //更新RET_WH_MTRL
                Ret_wh_mtrl ret_wh_mtrl = new Ret_wh_mtrl();
                rtnBeen = getRetWhMtrlFunc(ret_mtrl_aply.getMtrl_prod_id_fk(), ret_mtrl_aply.getMtrl_lot_id(),ret_mtrl_aply.getDest_shop());
                if (rtnBeen.getlRc() != _NORMAL) {
                	outTrx.setRtn_mesg(rtnBeen.getMsgBuf());
                    return rtnBeen.getlRc();
                } else {
                	ret_wh_mtrl = (Ret_wh_mtrl) rtnBeen.getObj();
                }
                ret_wh_mtrl.setEvt_qty(ret_wh_mtrl.getEvt_qty() - Double.valueOf(iary.getAct_repay_mtrl_qty()));
                retWhMtrlDao.update(ret_wh_mtrl);
            }else {
                outTrx.setRtn_mesg("备品备件申请信息不存在");
                return E_MTPMTRLAPY_MTRL_APLY_NOT_FOUND;
            }
        }
        return lRc;
    }
    
    private SimpleRtnBeen getRetWhMtrlFunc(String mtrl_prod_id, String mtrl_lot_id,String dest_shop){
    	SimpleRtnBeen rtnBeen = new SimpleRtnBeen();
        String hql ="From Ret_wh_mtrl where dest_shop='"+dest_shop+"' and mtrl_prod_id_fk ='" + mtrl_prod_id + "'";
        if(!Util.isSpaceCheck(mtrl_lot_id)){
        	hql += " and mtrl_lot_id='" + mtrl_lot_id + "'";
        }
        List<Ret_wh_mtrl>  ret_wh_mtrls = retWhMtrlDao.find(hql);
        if(ret_wh_mtrls.isEmpty()){
        	rtnBeen.setlRc(E_RET_WH_MTRL + E_READ_NOT_FOUND);
        	rtnBeen.setMsgBuf("未找到物料[" + mtrl_prod_id + "]的库存信息");
        	return rtnBeen;
        }else if(ret_wh_mtrls.size() > 1){
        	rtnBeen.setlRc(E_MTPMTRLAPY_INVALID_WH_INFO);
        	rtnBeen.setMsgBuf("物料[" + mtrl_prod_id + "]的库存信息不止一条，请确认");
        	return rtnBeen;
        }
        
        return new SimpleRtnBeen(ret_wh_mtrls.get(0));
    }
}

